﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;

namespace TaobaoLibrary
{
    public class JsonpParser
    {
        public static string ParseJsonpToString(string input)
        {
            bool isBody = false;
            int tie = 0;
            StringBuilder output = new StringBuilder();

            foreach (char ch in input)
            {
                if (ch == '(')
                {
                    tie++;
                    if (!isBody)
                    {
                        isBody = true;
                    }
                }
                else if (ch == ')')
                {
                    tie--;
                    if (tie == 0)
                    {
                        break;
                    }
                }
                else
                {
                    if (isBody)
                    {
                        output.Append(ch);
                    }
                }
            }
            return output.ToString();
        }

        public static JToken ParseJsonpToObject(string input)
        {
            string jsonString = ParseJsonpToString(input);
            return JToken.Parse(jsonString);
        }
    }
}
